package com.framework.component.resolver.handlebars;

import com.github.jknack.handlebars.Handlebars;
import com.github.jknack.handlebars.helper.HelperFunction;
import com.github.jknack.handlebars.internal.lang3.StringUtils;

import java.text.SimpleDateFormat;
import java.util.Date;

public class DefaultHelper {

    private static final String DATE_TIME_PATTERN = "yyyy-MM-dd HH:mm:ss";

    /**
     * 将数据转化为json可使用的值
     */
    @HelperFunction("value")
    public static Object valueString(Object value) {
        if (value instanceof Date) {
            return dateFormat((Date) value, null);
        }
        String val = value == null ? StringUtils.EMPTY : value.toString();
        return new Handlebars.SafeString("\"" + val + "\"");
    }

    /**
     * 时间格式化
     */
    @HelperFunction("dateFormat")
    public static Object dateFormat(Date value, String format) {
        if (value == null) {
            return valueString(value);
        }
        if (format == null) {
            format = DATE_TIME_PATTERN;
        }
        return valueString(dateToString(value, format));
    }

    private static String dateToString(Date date, String format) {
        SimpleDateFormat dateFormat = new SimpleDateFormat(format);
        return dateFormat.format(date);
    }
}
